package fun.codedesign.jdk.lang.stream;

import org.junit.Test;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class StreamTest {
    public static void main(String[] args) {

    }

    @Test
    public void stream() {
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        print(filtered);
        // forkjoin pool invoke
        strings.parallelStream().collect(Collectors.toSet());
    }

    @Test
    public void forEach() {
        Random rd = new Random();
        rd.ints().limit(10).forEach(System.out::println);
    }

    @Test
    public void map() {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 2);
        numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList());
    }

    @Test
    public void filter() {
        List<String> names = Arrays.asList("zhangsan", "lisi", "wangwu");
        names.stream().filter(s -> s.startsWith("zhang")).collect(Collectors.toList());
    }

    @Test
    public void limit() {
        forEach();
    }

    @Test
    public void sorted() {
        Random rd = new Random();
        rd.ints(10).sorted().forEach(System.out::println);
        System.out.println("---");
        rd.ints().limit(10).sorted().forEach(System.out::println);
    }

    @Test
    public void collectors() {
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

        System.out.println("筛选列表: " + filtered);
        String mergedString = strings.parallelStream().filter(s -> !s.isEmpty()).collect(Collectors.joining(", "));
        System.out.println("合并字符串: " + mergedString);
    }

    @Test
    public void count() {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 0, 3, 2, 1);
        IntSummaryStatistics statistics = numbers.stream().mapToInt(i -> i).summaryStatistics();
        print("平均数:" + statistics.getAverage());
        print("数字个数:" + statistics.getCount());
        print("最大数:" + statistics.getMax());
        print("最小数:" + statistics.getMin());
        print("所有数之和:" + statistics.getSum());
    }

    public void print(Object src) {
        System.out.println(src);
    }
}
